package com.power.strategy.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.power.config.WxParaConfig;
import com.power.constant.AuthConstants;
import com.power.domain.LoginMember;
import com.power.mapper.LoginMemberMapper;
import com.power.model.SecurityUser;
import com.power.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Description 商城购物系统登录具体实现类
 * @Author dingchunlin
 * @Date 2024/07/10 21:51
 * @Version 1.0.0
 */
@Service(AuthConstants.MEMBER_LOGIN)
public class MemberLoginStrategy  implements LoginStrategy {

    @Autowired
    private WxParaConfig wxParaConfig;

    @Autowired
    private LoginMemberMapper loginMemberMapper;

    @Override
    public UserDetails realLogin(String username) {
        // 获取登录凭证url
        String realUrl = String.format(wxParaConfig.getUrl(), wxParaConfig.getAppId(), wxParaConfig.getSecret(), username);
        // 调用微信接口获取用户信息
        String jsonStr = HttpUtil.get(realUrl);
        if (!StringUtils.hasText(jsonStr)){
            throw new InternalAuthenticationServiceException("登录失败，请稍后再试");
        }
        // 将响应的数据进行转换
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String oppenid = jsonObject.getString("openid");
        // 判断是否有值
        if (!StringUtils.hasText(oppenid)){
            throw new InternalAuthenticationServiceException("登录失败，请稍后再试");
        }
        // 根据appid查询用户信息
        LoginMember loginMember = loginMemberMapper.selectOne(new LambdaQueryWrapper<LoginMember>()
                .eq(LoginMember::getOpenId, oppenid));
        // 判断是否有值
        if (ObjectUtil.isNull(loginMember)){
            // 新增用户信息
            loginMember = registerMember(oppenid);
        }
        // 判断账号的状态
        if (!loginMember.getStatus().equals(1)){
            throw new InternalAuthenticationServiceException("账号已被禁用，请联系平台工作人员");
        }
        // 返回用户信息，供Spring Security进行验证
        SecurityUser securityUser = new SecurityUser();
        securityUser.setUserId(Long.valueOf(loginMember.getId()));
        securityUser.setLoginType(AuthConstants.MEMBER_LOGIN);
        securityUser.setUsername(oppenid);
        securityUser.setStatus(loginMember.getStatus());
        securityUser.setPassword(wxParaConfig.getPwd());
        securityUser.setOpenid(oppenid);
        return securityUser;
    }

    private LoginMember registerMember(String oppenid) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteAddr();

        LoginMember loginMember = new LoginMember();
        loginMember.setOpenId(oppenid);
        loginMember.setStatus(1);
        loginMember.setCreateTime(new Date());
        loginMember.setUpdateTime(new Date());
        loginMember.setUserLasttime(new Date());
        loginMember.setUserRegip(ip);
        loginMember.setUserLastip(ip);
        loginMember.setScore(0);
        // 保存用户信息
        loginMemberMapper.insert(loginMember);
        return loginMember;
    }

}
